/*
 * MainMenu_Controller.java
 * Final Project Example
 * Created on Oct 8, 2014, 10:58:26 PM
 * by Fairul Filza with Team FA_PemrogrammanLanjut
 */

package Controllers;

// <editor-fold defaultstate="collapsed" desc="Import Code">
import Interfaces.ControllersProcess_Interface;
import static Interfaces.ControllersProcess_Interface.FILE_EXIT;
import static Interfaces.ControllersProcess_Interface.HELP_ABOUT;
import static Interfaces.ControllersProcess_Interface.TOOLS_UNUSED;
import Models.Categories_Model;
import Models.Dvds_Model;
import Views.MainMenu_MainView;

import Views.MasterCd_EditView;
import Views.MasterCd_View;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
// </editor-fold>

/** @author PemrogrammanLanjut_LABIV_TI_05~09 */
public class MasterCd_Controller implements ControllersProcess_Interface {
    private MasterCd_View MenuView;
    private MasterCd_EditView EditView;
    private Calendar CurrentDate;
    private SimpleDateFormat DateForm;
    private int flag;


    // <editor-fold defaultstate="collapsed" desc="Constructor Code">
    public MasterCd_Controller(MasterCd_View MenuView) {
        this.MenuView = MenuView;
        tblData_componentShown();
    }
    public MasterCd_Controller(MasterCd_EditView EditView) {
        this.EditView = EditView;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Getter and Setter Code">
    public MasterCd_View getMenuView() {
        return MenuView;
    }

    public void setMenuView(MasterCd_View MenuView) {
        this.MenuView = MenuView;
    }
    public MasterCd_EditView getListView() {
        return EditView;
    }

    public void setEditView(MasterCd_EditView EditView) {
        this.EditView = EditView;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Method Code">
    private void tblData_componentShown() {
        Dvds_Model Model;
        DefaultTableModel Record;
        String[] Header;
        int[] wCol;

        Header = new String[] {"TITLE", "CODE", "CATEGORY", "STOCK", "PRICE", "DETAIL"};
        Model = new Dvds_Model();
        Model.showDataSet();
        Record = new DefaultTableModel(Model.getDataRecord(), Header){
            @Override
            public boolean isCellEditable(int row, int column) {
            //Only the third column
            return false;
        }
        };
        wCol = new int[]{300, 50,100 ,70 ,70, 150};
        MenuView.getTblData().setModel(Record);
        initColumnRecord(MenuView.getTblData(), wCol);
//        ListView.getTblData().addRowSelectionInterval(0, 0);
//        ListView.getLblCode().setText("");
        
        MenuView.getBtnNew().setIcon(new ImageIcon(getClass().getResource("/Images/new.png")));
        MenuView.getBtnNew().setEnabled(true);
        MenuView.getBtnEdit().setIcon(new ImageIcon(getClass().getResource("/Images/edit3.png")));
        MenuView.getBtnEdit().setEnabled(false);
        MenuView.getBtnDelete().setIcon(new ImageIcon(getClass().getResource("/Images/delete3.png")));
        MenuView.getBtnDelete().setEnabled(false);
    }

    private void tblData_mouseReleased() {
        Dvds_Model Model;
        String Value;
        int a=0;
        for(int i=0; i<6; i++){
            if(MenuView.getTblData().getColumnName(i).equals("CODE")){
                a= i;
                break;
            }
        }
        Value = MenuView.getTblData().getValueAt(MenuView.getTblData().getSelectedRow(), a).toString();
        Model = new Dvds_Model();;
        MenuView.getLblCode().setText(Value);
        MenuView.getBtnNew().setIcon(new ImageIcon(getClass().getResource("/Images/new2.png")));
        MenuView.getBtnNew().setEnabled(false);
        MenuView.getBtnEdit().setIcon(new ImageIcon(getClass().getResource("/Images/edit.png")));
        MenuView.getBtnEdit().setEnabled(true);
        MenuView.getBtnDelete().setIcon(new ImageIcon(getClass().getResource("/Images/delete.png")));
        MenuView.getBtnDelete().setEnabled(true);
    }
    
    private void btnMenu_mouseClick(int code) {
        switch(code) {
            case FILE_EXIT:
                System.exit(0);
                break;
            case TOOLS_UNUSED:
                break;
            case HELP_ABOUT:
                break;
        }
    }

    private void btnNew_mouseClick() {
        EditView = new MasterCd_EditView(MenuView.getMain(), "");
        frmEditor_componentShown("");
        EditView.setVisible(true);
        
    }
    private void btnEdit_mouseClick() {
        EditView = new MasterCd_EditView(MenuView.getMain(), MenuView.getLblCode().getText());
        frmEditor_componentShown(MenuView.getLblCode().getText());
        EditView.setVisible(true);
    }

    private void btnSave_mouseClick() {
        Dvds_Model Model;

        if(isValidate()) {
            Model = new Dvds_Model(EditView.getTxtCodeCd().getText(),
                                    EditView.getTxtTitle().getText(),
                                    EditView.getTxtDetail().getText(),
                                    Integer.parseInt(EditView.getTxtPrice().getText()),
                                    Integer.parseInt(EditView.getTxtStock().getText()),
                                    recordRequest(EditView.getCboCategory().getSelectedItem().toString(), "Description"));
            if(Model.addDataValue()) {
                JOptionPane.showMessageDialog(EditView, "Save Data Succesfully");
            } else {
                JOptionPane.showMessageDialog(EditView, "Save Data Failed");
            }
            resetText();
            EditView.getTxtCodeCd().setText(Model.genIdDataValue());
        }
    }
    
    private void btnEdit2_mouseClick() {
        Dvds_Model Model;

        if(isValidate()) {
            Model = new Dvds_Model(EditView.getTxtCodeCd().getText(),
                                    EditView.getTxtTitle().getText(),
                                    EditView.getTxtDetail().getText(),
                                    Integer.parseInt(EditView.getTxtPrice().getText()),
                                    Integer.parseInt(EditView.getTxtStock().getText()),
                                    recordRequest(EditView.getCboCategory().getSelectedItem().toString(), "Description"));
            if(Model.editDataValue()) {
                JOptionPane.showMessageDialog(EditView, "Save Data Succesfully");
            } else {
                JOptionPane.showMessageDialog(EditView, "Save Data Failed");
            }
            EditView.dispose();
        }
    }
    
    private void btnCancel_mouseClick(){
        EditView.dispose();
    }
    
    private void btnExit_mouseClick() {
        System.exit(0);
    }

    private void frmEditor_componentShown(String Code) {
        Dvds_Model Model;
        System.out.println("code = " + Code);
        if(!Code.matches("")) {
            try {
                Model = new Dvds_Model(Code);
                Model.showSelectedDataSet(Code, "DvdId");
                resetText();
                EditView.getTxtCodeCd().setText(Model.getDvdId());
                EditView.getTxtDetail().setText(Model.getDetail());
                EditView.getTxtTitle().setText(Model.getTitle());
                EditView.getTxtPrice().setText(String.valueOf(Model.getPrice()));
                EditView.getTxtStock().setText(String.valueOf(Model.getStock()));
                EditView.getCboCategory().setSelectedItem(Model.getCategories().getDescription());
                //EditView.getCboCategory().setSelectedItem(Model.getCategories().getDescription());
                EditView.getBtnEdit().setVisible(true);
                EditView.getBtnSave().setVisible(false);
                EditView.getLblWallpaper().setIcon(new ImageIcon(getClass().getResource("/Images/edit_revisi.png")));
            } catch(Exception ex) {
                System.out.println("[ERROR] - Dvds_Controller.frmEditor_componentShown at " + ex.getMessage());
            }
        } else {
            Model = new Dvds_Model();
            resetText();
            //EditView.getCboCategory().setSelectedItem("-<Choose One>-");
            EditView.getBtnSave().setVisible(true);
            EditView.getBtnEdit().setVisible(false);
            EditView.getTxtCodeCd().setText(Model.genIdDataValue());
            EditView.getTxtTitle().requestFocus();
            EditView.getLblWallpaper().setIcon(new ImageIcon(getClass().getResource("/Images/New_revisi.png")));
            
        }
    }
    
    private void btnDelete_mouseClick() {
        Dvds_Model Model;

        if(MenuView.getLblCode().getText().matches("")) {
            JOptionPane.showMessageDialog(MenuView, "Code is Empty");
        } else {
            if(JOptionPane.showConfirmDialog(null, "Are You Sure?", "Warning",
                           JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                Model = new Dvds_Model(MenuView.getLblCode().getText());
                if(Model.subDataValue()) {
                    MenuView.getLblCode().setText("");
                } else {
                    JOptionPane.showMessageDialog(null, "Delete Data Failed!");
                    MenuView.getLblCode().setText("");
                }
                tblData_componentShown();
            }
        }
    }
    
    private void fillCboCategory() {
        Categories_Model Model;
        String[] ComboModel;
        String[][] TmpRecord;
        int i;

        Model = new Categories_Model();
        Model.showDataSet();
        TmpRecord = Model.getDataRecord();
        ComboModel = new String[TmpRecord.length + 1];
        ComboModel[0] = "-<Choose One>-";
        for (i = 1; i < TmpRecord.length + 1; i++) {
            ComboModel[i] = TmpRecord[i - 1][1];
        }
        DefaultComboBoxModel Cbo = new DefaultComboBoxModel(ComboModel);
        EditView.getCboCategory().setModel(Cbo);
    }
    
    private boolean isValidate() {
        boolean flag;

        flag = false;
        if(EditView.getTxtCodeCd().getText().matches("")) {
            JOptionPane.showMessageDialog(EditView, "Code is Empty");
            EditView.getTxtCodeCd().requestFocus();
            flag = false;
        } else if(EditView.getTxtDetail().getText().matches("")) {
            JOptionPane.showMessageDialog(EditView, "Detail is Empty");
            EditView.getTxtDetail().requestFocus();
            flag = false;
        } else if(EditView.getTxtTitle().getText().matches("")) {
            JOptionPane.showMessageDialog(EditView, "Title is Empty");
            EditView.getTxtTitle().requestFocus();
            flag = false;
        }  else if(EditView.getTxtPrice().getText().matches("") || Integer.parseInt(EditView.getTxtPrice().getText()) <= 0) {
            JOptionPane.showMessageDialog(EditView, "Price is Empty");
            EditView.getTxtPrice().requestFocus();
            flag = false;
        } else if(EditView.getTxtStock().getText().matches("") || Integer.parseInt(EditView.getTxtStock().getText()) < 0) {
            JOptionPane.showMessageDialog(EditView, "Stock is Empty");
            EditView.getTxtStock().requestFocus();
            flag = false;
        } else if(EditView.getCboCategory().getSelectedIndex() <= 0) {
            JOptionPane.showMessageDialog(EditView, "Category Not be Chossen");
            EditView.getCboCategory().requestFocus();
            flag = false;
        } else {
            flag = true;
        }
        return flag;
    }
    
    private void resetText() {
        fillCboCategory();
        EditView.getTxtCodeCd().setText("");
        EditView.getTxtDetail().setText("");
        EditView.getTxtTitle().setText("");
        EditView.getTxtPrice().setText("");
        EditView.getTxtStock().setText("");
        //EditView.getCboCategory().setSelectedIndex(0);
        
    }
    
    private String recordRequest(String Value, String Key) {
        Categories_Model Model;
        String Result;

        Result = "";
        try {
            Model = new Categories_Model();
            Model.showSelectedDataSet(Value, Key);
            Result = Model.getCategoryId();
        } catch (Exception Ex) {
            System.out.println("[ERROR] - Dvds_Controller.recordRequest at " + Ex.getMessage());
        }
        return Result;
    }
    
    private void frmMain_windowClosing() {
        if(JOptionPane.showConfirmDialog(null, "Are You Sure?", "Warning",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }

    private void curDate_runtimeDate() {
        String Patern = null;

        CurrentDate = Calendar.getInstance();
        DateForm = new SimpleDateFormat("dd MMMM yyyy HH:mm");
        Patern = DateForm.format(CurrentDate.getTime());

        
    }
    private void initColumnRecord(JTable table, int[] wCol) {
        TableColumn col = null;
        int i = 0;
        for (i = table.getColumnCount() - 1; i > 0; i--) {
            col = table.getColumnModel().getColumn(i);
            col.setPreferredWidth(wCol[i]);
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Anonymous Code">
    public ComponentAdapter ViewComponent_Listener = new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent Evt) {
            if(Evt.getSource().equals(MenuView)) {
                if(!MenuView.isSearch()){
                    tblData_componentShown();
                }else{
                    MenuView.setSearch(false);
                }
            }
        }
    };
    public MouseAdapter ViewTable_Listener = new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent Evt) {
            if(Evt.getSource().equals(MenuView.getTblData())) {
                tblData_mouseReleased();
            }
        }
    };

    public KeyAdapter ViewKey_Listener = new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent Evt) {
            tblData_mouseReleased();
            if(Evt.getKeyCode() == KeyEvent.VK_ENTER) {
                btnEdit_mouseClick();
            }else if(Evt.getKeyCode() == KeyEvent.VK_DELETE){
                btnDelete_mouseClick();
            }
            
            
        }
    };

    
    public MouseAdapter ViewButtonImg_Listener = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent Evt) {
            if(Evt.getSource().equals(MenuView.getBtnNew())) {
                MenuView.getBtnNew().setIcon(new ImageIcon(getClass().getResource("/Images/new2.png")));
            } else if(Evt.getSource().equals(MenuView.getBtnEdit())) {
                MenuView.getBtnEdit().setIcon(new ImageIcon(getClass().getResource("/Images/edit2.png")));
            } else if(Evt.getSource().equals(MenuView.getBtnRefresh())) {
                MenuView.getBtnRefresh().setIcon(new ImageIcon(getClass().getResource("/Images/refresh2.png")));
            } else if(Evt.getSource().equals(MenuView.getBtnDelete())) {
                MenuView.getBtnDelete().setIcon(new ImageIcon(getClass().getResource("/Images/delete2.png")));
            } 
        }
        @Override
        public void mouseReleased(MouseEvent Evt) {
                  if(Evt.getSource().equals(MenuView.getBtnNew())) {
                MenuView.getBtnNew().setIcon(new ImageIcon(getClass().getResource("/Images/new.png")));
            } else if(Evt.getSource().equals(MenuView.getBtnEdit())) {
                MenuView.getBtnEdit().setIcon(new ImageIcon(getClass().getResource("/Images/edit.png")));
            } else if(Evt.getSource().equals(MenuView.getBtnRefresh())) {
                MenuView.getBtnRefresh().setIcon(new ImageIcon(getClass().getResource("/Images/refresh.png")));
            } else if(Evt.getSource().equals(MenuView.getBtnDelete())) {
                MenuView.getBtnDelete().setIcon(new ImageIcon(getClass().getResource("/Images/delete.png")));
            }
        }
    };
    
    public ActionListener ViewButton_Listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent Evt) {
            if(Evt.getSource().equals(MenuView.getBtnNew())) {
                btnNew_mouseClick();
            }else if(Evt.getSource().equals(MenuView.getBtnEdit())) {
                btnEdit_mouseClick();
            }else if(Evt.getSource().equals(MenuView.getBtnRefresh())) {
                tblData_componentShown();
                System.out.println("refresh");
            }else if(Evt.getSource().equals(MenuView.getBtnDelete())) {
                btnDelete_mouseClick();
            }
        }
    };
    
    public ComponentAdapter EditComponent_Listener = new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent Evt) {
            if(Evt.getSource().equals(EditView)) {
                if(EditView.getTxtCodeCd().getText().matches("")) {
                    frmEditor_componentShown("");
                }
            }
        }
    };
    
    public ActionListener EditButton_Listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent Evt) {
           if(Evt.getSource().equals(EditView.getBtnSave())){
                btnSave_mouseClick();
            }else if(Evt.getSource().equals(EditView.getBtnEdit())){
                btnEdit2_mouseClick();
            }else if(Evt.getSource().equals(EditView.getBtnCancel())){
                btnCancel_mouseClick();
            }
           
        }
    };

    public WindowAdapter EditWindow_Listener = new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent Evt) {
            frmMain_windowClosing();
        }
    };

    public MouseAdapter EditButtonImg_Listener = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent Evt) {
            
        }

        @Override
        public void mouseReleased(MouseEvent Evt) {
       
        }
    };

    public ActionListener CurrentDate_ActListener = new ActionListener() {
       @Override
        public void actionPerformed(ActionEvent Evt) {
            curDate_runtimeDate();
        }
    };

    public ActionListener LabelAnimate_ActListener = new ActionListener() {
        int i = (-530 / 2); // Sumber Bedasarkan panjang label yang akan di gerakan

        @Override
        public void actionPerformed(ActionEvent e) {
            i++;  // Pergerakan text untuk Motion Maju

            if(i == 530) i = -530; // Jika sudah mencapai titik akhir text kembali ke awal

            // Untuk Text bekedip
            if(i % 20 == 0) {  // Untuk setiap hitungan per 10
              //  MenuView.getLblContext().setSize((MenuView.getLblContext().getWidth() == 0) ? 185 : 0, 32); // Kedipkan text
            }
            //MenuView.getLblTitle().setLocation(i + 10, 0);  // Pergerakan Text
        }
    };
    // </editor-fold>
}
// End of Code